package com.sanchunhui.psc.utils

import java.io.UnsupportedEncodingException
import kotlin.experimental.and

/**
 * 字符串转字节工具类
 */
object HexUtil {

    fun hexStringToBytes(hexString: String?): ByteArray? {
        var hexString = hexString
        if (hexString == null || hexString == "") {
            return null
        }
        hexString = hexString.toUpperCase()
        val length = hexString.length / 2
        val hexChars = hexString.toCharArray()
        val d = ByteArray(length)
        for (i in d.indices) {
            val pos = i * 2
            d[i] = (charToByte(hexChars[pos]).toInt() shl 4 or charToByte(hexChars[pos + 1]).toInt()).toByte()
        }
        return d
    }


    fun deviceNameToBytes(devNameHexStr: String?): ByteArray? {
        var devNameHexStr = devNameHexStr
        if (devNameHexStr == null || devNameHexStr == "") {
            return null
        }
        var fhHexStr : String = "6805" // 帧头
        var ftHexStr : String = "0d" // 帧尾
        val devNameByteArray : ByteArray = toUtf8(devNameHexStr)!!
        fhHexStr = fhHexStr.toUpperCase()
        ftHexStr = ftHexStr.toUpperCase()
        val fhLength = fhHexStr.length / 2
        val ftLength = ftHexStr.length / 2
        val fhHexChars = fhHexStr.toCharArray()
        val ftHexChars = ftHexStr.toCharArray()
        val d = ByteArray(fhLength+ftLength+devNameByteArray.size)
        for (i in 0 until  fhLength) {
            val pos = i * 2
            d[i] = (charToByte(fhHexChars[pos]).toInt() shl 4 or charToByte(fhHexChars[pos + 1]).toInt()).toByte()
        }
        var j : Int = fhLength
        for (i in 0 until devNameByteArray.size) {
            d[j] = devNameByteArray[i]
            if (i == devNameByteArray.size-1) {
                break
            }
            j = j + 1
        }
        for (i in 0 until  ftLength) {
            val pos = i * 2
            d[j+1] = (charToByte(ftHexChars[pos]).toInt() shl 4 or charToByte(ftHexChars[pos + 1]).toInt()).toByte()
        }
        return d
    }

    fun toUtf8(str: String): ByteArray? {
        var bytes: ByteArray? = null
        try {
            bytes = str.toByteArray(charset("utf-8"))
        } catch (e: UnsupportedEncodingException) {
            // TODO Auto-generated catch block
            e.printStackTrace()
        }

        return bytes
    }

    private fun charToByte(c: Char): Byte {
        return "0123456789ABCDEF".indexOf(c).toByte()
    }

    fun bytesToHexString(b: ByteArray): String? {
        if (b.size == 0) {
            return null
        }
        val sb = StringBuilder("")
        for (i in b.indices) {
            val value = b[i] and 0xFF.toByte()
            val hv = value.toString()
            if (hv.length < 2) {
                sb.append(0)
            }

            sb.append(hv)
        }
        return sb.toString()
    }
}
